package com.zhkj.txg.module.home.ui

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.txg.R
import com.zhkj.txg.module.home.vm.MallCategoryViewModel
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.module.home.adapter.MallCategoryProductAdapter
import kotlinx.android.synthetic.main.fragment_mall_cate.*

class MallCategoryProductFragment : ViewModelFragment<MallCategoryViewModel>() {
    companion object {
        private val ID = "id"
        fun getInstance(id: Int) = MallCategoryProductFragment().apply {
            val bundle = Bundle()
            bundle.putInt(ID, id)
            arguments = bundle
        }
    }

    override fun setViewModel(): MallCategoryViewModel = createViewModel(false)
    override val layoutResId: Int = R.layout.fragment_mall_cate

    private val productAdapter = MallCategoryProductAdapter().apply {
        loadMoreModule?.isEnableLoadMore = true
        loadMoreModule?.setOnLoadMoreListener {
            viewModel.mallCategory(AccountManager.getToken(), 1)
        }
    }

    override fun initUI() {
        with(rvMallCate) {
            layoutManager = GridLayoutManager(activity, 3)
            adapter = productAdapter
            setPadding(ScreenUtil.dip(context, 10), ScreenUtil.dip(context, 10), 0, 0)
        }
        productAdapter.setEmptyView(R.layout.layout_empty_data)
    }

    override fun initViewModel() {
        viewModel.cateId = arguments?.getInt(ID) ?: 0
        viewModel.shopListLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.data?.let {
                    // 数据填充
                    if (it.loadMore) productAdapter.addData(it.goods)
                    else productAdapter.setNewData(it.goods)
                    // 判断加载状态
                    if (it.hasMore) productAdapter.loadMoreModule?.loadMoreComplete()
                    else productAdapter.loadMoreModule?.loadMoreEnd()
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    productAdapter.loadMoreModule?.loadMoreFail()
                }
            }
        })
    }

    override fun initData() {
        viewModel.mallCategory(AccountManager.getToken(), 1)
    }
}